class RateController < ApplicationController
	def index
		if authorize
			if session[:loginrole] == "Admin"
				@dashboard = "Go to Gradebook"
			end
		end
		
		@profName = getProfName
		
		if(session[:performance].nil?)
			@performance = ""
		else
			@performance = session[:performance]
		end
		
		if(session[:improvement].nil?)
			@improvement = ""
		else
			@improvement = session[:improvement]
		end
		
		if(session[:hours].nil?)
			@hours = ""
		else
			@hours = session[:hours]
		end
	end
	
	def getProfName
		user = User.find(:first, :conditions => [ "role = ?", 1])
		person = Person.find(:first, :conditions => ["id = ?", user.id])
		"#{person.firstname} #{person.surname}"
	end
	

	
	def authorize 
		unless session[:loggedin] == true
			flash[:notice] = "Please log in" 
			redirect_to :controller => :login, :action => :index
		end
		return true 
	end 
	
	# submit ratings to the database
	def submitRatings
		
		if(params[:performance] == "")
			saveData params
			flash[:notice] = "Performance evalution is empty"
			redirect_to :controller => :rate, :action => :index
			return
		end
		
		if(params[:hours] == "")
			daveData params
			flash[:notice] = "Hours spent on the course is empty"
			redirect_to :controller => :rate, :action => :index
			return
		end
				count = Rating.count
		Rating.create(:performance => params[:performance], :improvement => params[:improvement], :hours => params[:hours])
		if(count >= Rating.count)
			saveData params
			flash[:notice] = "Hours is not a number"
			redirect_to :controller => :rate, :action => :index
			return
		else
			RatingSubmitted.create(:person_id => session[:loginuid])
			session[:performance] = nil
			session[:improvement] = nil
			session[:hours] = nil
			flash[:notice] = "Ratings submitted"
			redirect_to :controller => :rate, :action => :index
			return
		end
	end
	
  def Delete_all_rates
    @entries = Rating.find(:all)
    if not @entries.nil?
        @entries.each{|rate|
            rate.delete
        }
    end
    @entries = RatingSubmitted.find(:all)
    if not @entries.nil?
        @entries.each{|rateSub|
            rateSub.delete
        }
    	flash[:notice] = "All ratings have been deleted."
    end
	redirect_to :controller => :rate, :action => :index
  end

	private
	def saveData params
		session[:performance] = params[:performance]
		session[:improvement] = params[:improvement]
		session[:hours] = params[:hours]
	end
	
end
